//
//  MusicDetailsViewController.m
//  DayByDay
//
//  Created by dllo on 16/5/15.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "MusicDetailsViewController.h"
#import "STKAudioPlayerHandle.h"
#import "PosterDetailSongsModel.h"
#import <UIImageView+WebCache.h>
#import <AFNetworking.h>
#import "AuditionListModel.h"
#import "lrcIDModel.h"
#import "LrcModel.h"
#import "DataHandle.h"
//#import "UMSocialSnsPlatformManager.h"

@interface MusicDetailsViewController ()<UITableViewDelegate, UITableViewDataSource>
- (IBAction)storeAction:(UIButton *)sender;

@property (strong, nonatomic) IBOutlet UIButton *storeBtn;
@property (nonatomic, strong)STKAudioPlayer *audioPlayer;
@property (strong, nonatomic) IBOutlet UILabel *currentLabel;
@property (strong, nonatomic) IBOutlet UILabel *AllTimeLabel;
- (IBAction)CircleStyleBtn:(id)sender;
- (IBAction)VolumeBtn:(id)sender;
@property (strong, nonatomic) IBOutlet UIButton *PlayOrPauseBtn;

- (IBAction)lastBtn:(id)sender;
- (IBAction)nextBtn:(id)sender;
@property (strong, nonatomic) IBOutlet UIImageView *backgrImageV;

@property (strong, nonatomic) IBOutlet UISlider *TImerSlider;
@property (strong, nonatomic) IBOutlet UIImageView *imageV;

- (IBAction)PresentBth:(id)sender;

@property (strong, nonatomic) IBOutlet UIButton *circleBtn;
@property (nonatomic, assign)BOOL isRotation;
@property (nonatomic, strong)NSMutableArray *lrcIdArray;
@property (nonatomic, strong)NSMutableArray *lrcArr;
@property (nonatomic, strong)NSMutableArray *timeArr;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSArray *myArr;
@property (nonatomic, strong)NSTimer *timer;
@property (nonatomic, assign)BOOL loaded;
@property (nonatomic, assign)BOOL isShare;
//@property (strong, nonatomic) IBOutlet UIView *shareView;
//@property (strong, nonatomic) IBOutlet UIButton *loginBtn;
//- (IBAction)loginBtn:(UIButton *)sender;
//- (IBAction)shareBtn:(id)sender;
@property (strong, nonatomic) IBOutlet UIView *shareView;
@property (strong, nonatomic) IBOutlet UIButton *loginbtn;
- (IBAction)loginBtn:(id)sender;

@property (strong, nonatomic) IBOutlet UIButton *shareBth;
- (IBAction)shareBtn:(UIButton *)sender;
@property (strong)NSArray *myTimeArr;
@property (strong)NSArray *myLrcArr;



@end

@implementation MusicDetailsViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSLog(@"+++++++111");
//    self.isRotation = YES;
    if (!self.isShare) {
        self.isRotation = YES;
        [self createView];
    }
//    self.isRotation = YES;
//    [self createView];
    if ([[[STKAudioPlayerHandle shareSTKAudioPlayerHandle] audioPlayer] state] == STKAudioPlayerStatePlaying) {
        [self.PlayOrPauseBtn setImage:[UIImage imageNamed:@"Unknown-6"] forState:UIControlStateNormal];
    } else {
        [self.PlayOrPauseBtn setImage:[UIImage imageNamed:@"Unknown-5"] forState:UIControlStateNormal];
    }
    
    self.isShare = NO;
    [self setCircleBtnImage];
    
//    self.isRotation = YES;
//    [self createView];
//    [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] addObserver:self forKeyPath:@"mutableArray" options:NSKeyValueChangeOldKey || NSKeyValueChangeNewKey context:nil];
    
}

- (void)setCircleBtnImage {
    if ([[STKAudioPlayerHandle shareSTKAudioPlayerHandle] audioPlayerStyle] == STKAudioPlayerAllLoop) {
        [self.circleBtn setImage:[UIImage imageNamed:@"Unknown-4"] forState:UIControlStateNormal];
    } else if ([[STKAudioPlayerHandle shareSTKAudioPlayerHandle] audioPlayerStyle] == STKAudioPlayerPlayminiSingleLoop) {
        [self.circleBtn setImage:[UIImage imageNamed:@"Unknown-2"] forState:UIControlStateNormal];
    } else if ([[STKAudioPlayerHandle shareSTKAudioPlayerHandle] audioPlayerStyle] == STKAudioPlayerRandom) {
        [self.circleBtn setImage:[UIImage imageNamed:@"Unknown-3"] forState:UIControlStateNormal];
    }
}

- (void)createView {
    PosterDetailSongsModel *model = self.array[self.currentOfMusic];
    [self.backgrImageV sd_setImageWithURL:[NSURL URLWithString:model.picUrl]];
    [self.imageV sd_setImageWithURL:[NSURL URLWithString:model.picUrl]];
//    UIVisualEffectView *effectView= [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]];
//    effectView.frame = self.view.frame;
//    effectView.alpha = 0.8;
    
    UIVisualEffectView* effectView = [[UIVisualEffectView alloc] initWithFrame:self.view.bounds];
    effectView.effect = nil;
    [UIView animateWithDuration:0.3 animations:^{
        effectView.effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        effectView.layer.opacity = 0.9;

    }];
    [self.backgrImageV addSubview:effectView];
    self.backgrImageV.frame = [UIScreen mainScreen].bounds;
//    self.backgrImageV.alpha = 0.8;
//    [self.imageV sd_setImageWithURL:[NSURL URLWithString:model.picUrl]];
    [self createAnimation];
    self.imageV.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    
    [self.imageV addGestureRecognizer:tap];
    [self rotationOrStop];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.imageV.frame.origin.y + 50 / 736.0 * HEIGHT + self.imageV.frame.size.height / 736.0 * HEIGHT, WIDTH / 3 * 2, 80 / 736.0 * HEIGHT) style:UITableViewStylePlain];
//    self.imageV.frame.size.height
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = [UIColor redColor];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = 0;
//    self.shareView.frame = CGRectMake(0, HEIGHT, WIDTH, 47);
    UIButton *button = [self.view viewWithTag:99999];
    button.hidden = YES;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.myLrcArr.count;
}
#warning ta
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class])];
//    cell.backgroundColor = [UIColor blueColor];
//    NSLog(@"+++++++++++%@",self.timeArr);
//    NSLog(@"-------------%@",self.lrcArr);
//    NSLog(@"===== %@",self.myTimeArr);
//    NSLog(@"=====333f %@",self.myLrcArr);

    cell.textLabel.text = self.myLrcArr[indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.textColor = [UIColor blackColor];
    cell.selectionStyle = 0;
//    NSLog(@"%@",self.lrcArr[indexPath.row]);
    return cell;
}

- (void)createAnimation {
    NSLog(@"11111");
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation.duration = 5;
    animation.repeatCount = NSIntegerMax;
    animation.fromValue = @(0);
    animation.toValue = @(M_PI * 2);
    animation.cumulative = YES;
    [self.imageV.layer addAnimation:animation forKey:@"animation"];
    
    
    
}

- (void)tapAction:(UITapGestureRecognizer *)tap {
    self.isRotation = !self.isRotation;
    
    [self rotationOrStop];
    [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] pauseOrResumePlayer];
    if (!self.isRotation) {
        [self.PlayOrPauseBtn setImage:[UIImage imageNamed:@"Unknown-5"] forState:UIControlStateNormal];
    } else {
        [self.PlayOrPauseBtn setImage:[UIImage imageNamed:@"Unknown-6"] forState:UIControlStateNormal];
    }
}

- (void)rotationOrStop {
    if (self.isRotation) {
        NSLog(@"asdfkjdsjkfdsf");
        [self rotation];
    } else {
        [self stop];
    }
}

- (void)rotation {
    CFTimeInterval stopTime = self.imageV.layer.timeOffset;
    self.imageV.layer.timeOffset = 0;
    self.imageV.layer.beginTime = 0;
    self.imageV.layer.speed = 1;
    self.imageV.layer.beginTime = [self.imageV.layer convertTime:CACurrentMediaTime() fromLayer:nil] - stopTime;
}

- (void)stop {
    CFTimeInterval stopTime = [self.imageV.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    self.imageV.layer.speed = 0;
    self.imageV.layer.timeOffset = stopTime;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    self.isRotation = YES;
//    [self createView];
    self.audioPlayer = [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] audioPlayer];
    [self.TImerSlider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    // 创建表
    
    [[DataHandle shareDataBaseHandle] createTableWithName:@"store"];
//    [[DataHandle shareDataBaseHandle] dropTable:@"store"];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getCurrentIndexPath:) name:@"playMusic" object:nil];
    self.TImerSlider.maximumValue = self.audioPlayer.duration;
    self.TImerSlider.value = self.audioPlayer.progress;
    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [self.PlayOrPauseBtn addTarget:self action:@selector(PlayOrPauseBtn:) forControlEvents:UIControlEventTouchUpInside];
    [NSThread detachNewThreadSelector:@selector(threaderAction:) toTarget:self withObject:nil];
    [self addObserver:self forKeyPath:@"currentOfMusic" options:NSKeyValueChangeOldKey || NSKeyValueChangeNewKey context:nil];
    [self lrc:[[STKAudioPlayerHandle shareSTKAudioPlayerHandle] currentOfMusic]];
    [self.tableView reloadData];
    [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] addObserver:self forKeyPath:@"mutableArray" options:NSKeyValueChangeOldKey || NSKeyValueChangeNewKey context:nil];
    [self checkStore];
    [self.view addSubview:self.shareView];
    self.shareView.frame = CGRectMake(0, HEIGHT , WIDTH, 47);
    NSLog(@"%f",self.shareView.frame.origin.y);
    self.imageV.layer.cornerRadius = WIDTH * 0.3;
    
//    self.isRotation = YES;
//    [self createView];
//    self.isRotation = YES;
//    [self createView];
//    [self createAnimation];
//    [self rotation];
//    NSLog(@"%f",self.imageV.frame.size.width);
}

- (void)checkStore {
    NSLog(@"11111");
    PosterDetailSongsModel *model = self.array[self.currentOfMusic];
//    AuditionListModel *listModel = model.auditionList.lastObject;
    if ([[DataHandle shareDataBaseHandle] selectPosterSongsModelFromTable:@"store" PrimaryKey:[NSString stringWithFormat:@"%@",model.songId]]) {
        NSLog(@"%@",model.songId);
        [self.storeBtn setImage:[UIImage imageNamed:@"439"] forState:UIControlStateNormal];
        self.storeBtn.selected = YES;
    } else {
        [self.storeBtn setImage:[UIImage imageNamed:@"438"] forState:UIControlStateNormal];
        self.storeBtn.selected = NO;
    }
}
   

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (!self.isShare) {
        NSLog(@"sdfsjdf");
        [self.timer invalidate];
        self.timer = nil;
        [self removeObserver:self forKeyPath:@"currentOfMusic"];
        [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] removeObserver:self forKeyPath:@"mutableArray"];
    }
    
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
//    NSLog(@"=========================sadkfkldsfjksdlf");
    if ([keyPath isEqualToString:@"currentOfMusic"]) {
        NSLog(@"%@",change);
//        [STKAudioPlayerHandle shareSTKAudioPlayerHandle].audioPlayer.duration
        self.AllTimeLabel.text = [NSString stringWithFormat:@"%0d:%.2f",(int)([STKAudioPlayerHandle shareSTKAudioPlayerHandle].audioPlayer.duration) / 60, [STKAudioPlayerHandle shareSTKAudioPlayerHandle].audioPlayer.duration - ((int)([STKAudioPlayerHandle shareSTKAudioPlayerHandle].audioPlayer.duration) / 60) * 60.0];
        [self lrc:[[STKAudioPlayerHandle shareSTKAudioPlayerHandle] currentOfMusic]];
//        NSLog(@"%d",[NSThread isMainThread]);
        [self.tableView reloadData];
        PosterDetailSongsModel *model = self.array[[[STKAudioPlayerHandle shareSTKAudioPlayerHandle] currentOfMusic]];
//        NSLog(@"%@",model.picUrl);
        [self.backgrImageV sd_setImageWithURL:[NSURL URLWithString:model.picUrl]];
        [self.imageV sd_setImageWithURL:[NSURL URLWithString:model.picUrl] placeholderImage:[UIImage imageNamed:@"cm2_default_cover_play"]];
    }
    if ([keyPath isEqualToString:@"mutableArray"]) {
//        NSLog(@"skdfkdlsf");
        self.array = [change valueForKey:@"mutableArray"];
    }
    [self checkStore];
}
//把timer添加到子线程中去;
- (void)threaderAction:(NSThread *)thread {
    NSLog(@"1111sfsdf");
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timeAction:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
}

- (void)timeAction:(NSTimer *)timer {
//    NSLog(@"%f",self.audioPlayer.progress);
//    NSLog(@"11");
    if (self.loaded) {
//        NSLog(@"1")
//        NSLog(@"sajkdfkdjsf");
        NSString *str;
        if (self.audioPlayer.progress - (int)(self.audioPlayer.progress / 60) * 60 < 10) {
            str = [NSString stringWithFormat:@"0%d:0%.1f",(int)(self.audioPlayer.progress / 60),self.audioPlayer.progress - (int)(self.audioPlayer.progress / 60) * 60];
        } else {
            str = [NSString stringWithFormat:@"0%d:%.1f",(int)(self.audioPlayer.progress / 60),self.audioPlayer.progress - (int)(self.audioPlayer.progress / 60) * 60];
        }
        
        //    NSLog(@"%@",str);
        //    NSLog(@"%@",str);
        if (self.timeArr.count > 0) {
            
//            NSLog(@"===== %@",self.myTimeArr);
//            NSLog(@"%@",self.myLrcArr);
            
            for (int i = 0; i < self.myTimeArr.count; i++) {
                
                if ([self.myTimeArr[i] hasPrefix:str]) {
                    //                NSLog(@"%d",i);
                    if (!self.isShare) {
                        
                        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
                        UITableViewCell *cell =  [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
                        cell.textLabel.textColor = [UIColor redColor];
                    }
                }
            }
            
        }
    }
//    for (int i = 0; i < self.timeArr.count; i++) {
//        
//        
//        if ([self.timeArr[i] hasPrefix:str]) {
//            NSLog(@"%d",i);
//            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
//        }
//    }
}

- (void)PlayOrPauseBtn:(UIButton *)button {
    [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] pauseOrResumePlayer];
        if ([[[STKAudioPlayerHandle shareSTKAudioPlayerHandle] audioPlayer] state] == STKAudioPlayerStatePlaying) {
            [button setImage:[UIImage imageNamed:@"Unknown-6"] forState:UIControlStateNormal];
        } else {
            [button setImage:[UIImage imageNamed:@"Unknown-5"] forState:UIControlStateNormal];
        }
    self.isRotation = !self.isRotation;
    [self rotationOrStop];

}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)CircleStyleBtn:(id)sender {
    UIButton *button = sender;
    [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] setPlayerPlayStyle];
    if ([[STKAudioPlayerHandle shareSTKAudioPlayerHandle] audioPlayerStyle] == STKAudioPlayerAllLoop) {
        [button setImage:[UIImage imageNamed:@"Unknown-4"] forState:UIControlStateNormal];
    } else if ([[STKAudioPlayerHandle shareSTKAudioPlayerHandle] audioPlayerStyle] == STKAudioPlayerPlayminiSingleLoop) {
        [button setImage:[UIImage imageNamed:@"Unknown-2"] forState:UIControlStateNormal];
    } else if ([[STKAudioPlayerHandle shareSTKAudioPlayerHandle] audioPlayerStyle] == STKAudioPlayerRandom) {
        [button setImage:[UIImage imageNamed:@"Unknown-3"] forState:UIControlStateNormal];
    }
    
}

- (IBAction)VolumeBtn:(id)sender {
    [UIView animateWithDuration:0.2 animations:^{
        NSLog(@"111111");
        self.shareView.frame = CGRectMake(0, HEIGHT - 47, WIDTH, 47);
    }];
}

- (IBAction)lastBtn:(id)sender {
    
    [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] lastSonger];
    
    [self.PlayOrPauseBtn setImage:[UIImage imageNamed:@"Unknown-6"] forState:UIControlStateNormal];
    self.isRotation = YES;
    [self rotationOrStop];
}

- (IBAction)nextBtn:(id)sender {
    
    [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] nextSonger];
    [self.PlayOrPauseBtn setImage:[UIImage imageNamed:@"Unknown-6"] forState:UIControlStateNormal];
    self.isRotation = YES;
    [self rotationOrStop];
//    [self positonOfCurrentMusicWith:YES];
//    PosterDetailSongsModel *model = self.array[[[STKAudioPlayerHandle shareSTKAudioPlayerHandle] currentOfMusic]];
//    [self.backgrImageV sd_setImageWithURL:[NSURL URLWithString:model.picUrl]];
//    [self.imageV sd_setImageWithURL:[NSURL URLWithString:model.picUrl] placeholderImage:[UIImage imageNamed:@"cm2_default_cover_play"]];
//    [self lrc:[[STKAudioPlayerHandle shareSTKAudioPlayerHandle] currentOfMusic]];
//    [self.tableView reloadData];
}

- (void)lrc:(NSInteger)lrc {
    self.loaded = NO;
    self.lrcArr = [NSMutableArray array];
    self.timeArr = [NSMutableArray array];
    self.myLrcArr = nil;
    self.myTimeArr = nil;
    PosterDetailSongsModel *model = self.array[lrc];
    AuditionListModel *audioModel = model.auditionList.lastObject;
    NSString *str =[NSString stringWithFormat:@"http://search.dongting.com/lyric/search?&title=%@&song_id=%@&artist=%@&filename=&duration_ms=%@",model.name, model.songId, model.singerName, audioModel.duration];
    NSString *urlEncode = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//    NSLog(@"%@",urlEncode);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:urlEncode parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.lrcIdArray = [NSMutableArray array];
        for (NSDictionary *dic in [responseObject valueForKey:@"data"]) {
            lrcIDModel *model = [lrcIDModel new];
            [model setValuesForKeysWithDictionary:dic];
            [self.lrcIdArray addObject:model];
        }
        //http://search.dongting.com/lyric/content?sign=1aa463c9af603ba64561a50d88b55695&song_id=42160309&lrcid=9963257&type=7&artist=Tiffany&title=I%20Just%20Wanna%20Dance&app=ttpod&v=v9.0.1.2016050614&user_id=0&mid=iPhone7%2C2&f=f320&s=s310&imsi=&hid=&splus=9.3.1&active=1&net=2&openudid=5e6106cc8d5bcf35f60a2997c79a00bb5a7c631f&idfa=ABDADD65-0877-4840-B14F-DFC8D1114AB0&utdid=VzR0dwnWYs8DANbYJ8SsFzOU&alf=(null)&bundle_id=com.ttpod.music&latitude=-1&longtitude=-1&access_token=(null)&vc=9000100
        // http://search.dongting.com/lyric/content?song_id=42160309&lrcid=9963257&type=7&artist=Tiffany&title=I%20Just%20Wanna%20Dance
        AFHTTPSessionManager *lrcmanager = [AFHTTPSessionManager manager];
        NSString *lrcStr = [NSString stringWithFormat:@"http://search.dongting.com/lyric/content?song_id=%@&lrcid=%@&type=%@&artist=%@&title=%@",model.songId,[self.lrcIdArray.firstObject _id], [self.lrcIdArray.firstObject myType], model.singerName, model.name];
        NSString *lrcEncode = [lrcStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//        NSLog(@"%@",lrcEncode);
        [lrcmanager GET:lrcEncode parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            NSLog(@"%@",responseObject);
            
            if (![[responseObject valueForKey:@"data"] isKindOfClass:[NSDictionary class]]) {
                return ;

            }
            
               
            
                LrcModel *lmodel = [LrcModel new];
                
//                NSLog(@"%@",[responseObject valueForKey:@"data"]);
                [lmodel setValuesForKeysWithDictionary:[responseObject valueForKey:@"data"]];
//                NSLog(@"dsfdsfslf");
                // 在子线程中完成字符串的转化操作.
                dispatch_queue_t global = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                dispatch_async(global, ^{
                    
                    [self dueLrc:lmodel.content];
                    
                });

            
//                LrcModel *lmodel = [LrcModel new];
//            NSLog(@"%@",[responseObject valueForKey:@"data"]);
//                [lmodel setValuesForKeysWithDictionary:[responseObject valueForKey:@"data"]];
//            NSLog(@"dsfdsfslf");
//            // 在子线程中完成字符串的转化操作.
//          dispatch_queue_t global = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//            dispatch_async(global, ^{
//               
//                [self dueLrc:lmodel.content];
//                
//            });
         
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
//            NSLog(@"%@",error);
            
        }];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
    
}

- (void)dueLrc:(NSString *)lrc {
    NSMutableArray *array = [NSMutableArray arrayWithArray:[lrc componentsSeparatedByString:@"\n"]];
//    NSLog(@"%@",array);
    NSMutableArray *newArray = [NSMutableArray array];
    for (int i = 0; i< array.count; i++) {
        
        id object = [array objectAtIndex:i];
        NSString *string = [NSString stringWithFormat:@"%@",object];
        if ([string hasPrefix:@"[x-trans]"]) {
            [array removeObject:string];
            continue;
        }
        int i = 1;
        NSMutableString *mutableStr = [NSMutableString stringWithString:string];
            while (i) {
                NSRange range = [mutableStr rangeOfString:@"<"];
                
                NSRange endRange = [mutableStr rangeOfString:@">"];
                
                if (range.length == 0) {
                    i = 0;
                } else{
                    [mutableStr replaceCharactersInRange:NSMakeRange(range.location, endRange.location - range.location + 1) withString:@""];
                }
//                NSLog(@"%@",mutableStr);
        }
        [newArray addObject:mutableStr];
        
    }
//    self.lrcArr = [NSMutableArray array];
//    self.timeArr = [NSMutableArray array];
    self.myArr = newArray;
    for (NSString *newStr1 in self.myArr) {
//        NSLog(@"=====%@",newStr1);
        if (![newStr1 isEqualToString:@""]) {
            NSArray *lrcArr = [newStr1 componentsSeparatedByString:@"]"];
            [self.lrcArr addObject:lrcArr.lastObject];
            NSString *timeStr = lrcArr.firstObject;
            [self.timeArr addObject:[timeStr substringFromIndex:1]];
        }
//        NSArray *lrcArr = [newStr1 componentsSeparatedByString:@"]"];
//        [self.lrcArr addObject:lrcArr.lastObject];
//        NSString *timeStr = lrcArr.firstObject;
//        [self.timeArr addObject:[timeStr substringFromIndex:1]];
        
    }
//    int range = 0;
//    for (int i = 0; i < self.lrcArr.count; i++) {
//        if (![self.lrcArr[i] isEqualToString:@""]) {
//            NSLog(@"sadjkfsdkjf");
//            break;p
//        }
//        NSLog(@"%@",self.lrcArr[i]);
//        [self.lrcArr removeObjectAtIndex:i];
//        range = i;
//    }
//    NSLog(@"%d",range);
//    [self.timeArr removeObjectsInRange:NSMakeRange(0, range + 1)];
//    [self.lrcArr removeObjectsInRange:NSMakeRange(0, range + 3)];

    // 回到主线程.
    dispatch_queue_t mainQ = dispatch_get_main_queue();
    dispatch_async(mainQ, ^{
//        NSLog(@"%@",self.lrcArr);
//        NSLog(@"%@",self.timeArr);
        self.myTimeArr = [NSArray arrayWithArray:self.timeArr];
        self.myLrcArr = [NSArray arrayWithArray:self.lrcArr];
        self.loaded = YES;
        [self.tableView reloadData];
        
    });
}

- (void)positonOfCurrentMusicWith:(BOOL)current {
    if (current) {
        if (self.currentOfMusic == self.array.count - 1) {
            self.currentOfMusic = 0;
        } else {
            self.currentOfMusic++;
        }
    }else {
        if (self.currentOfMusic == 0) {
            self.currentOfMusic = self.array.count - 1;
        } else {
            self.currentOfMusic --;
        }
    }
}

- (IBAction)PresentBth:(id)sender {
    self.isShare = NO;
    [self dismissViewControllerAnimated:YES completion:^{
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"Animation" object:nil];
    }];
}

- (void)sliderAction:(UISlider *)slider {
    [self.audioPlayer seekToTime:slider.value];
    if (slider.value == slider.maximumValue) {
//        NSLog(@"1111111111111111111111ksafjksdfjsd;fsdkf");
//        [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] nextSonger];
        PosterDetailSongsModel *model = self.array[[[STKAudioPlayerHandle shareSTKAudioPlayerHandle] currentOfMusic]];
        [self.backgrImageV sd_setImageWithURL:[NSURL URLWithString:model.picUrl]];
        [self.imageV sd_setImageWithURL:[NSURL URLWithString:model.picUrl] placeholderImage:[UIImage imageNamed:@"cm2_default_cover_play"]];
        [self lrc:[[STKAudioPlayerHandle shareSTKAudioPlayerHandle] currentOfMusic]];
        [self.tableView reloadData];
        
    }
    self.currentLabel.text = [NSString stringWithFormat:@"%0d:%.2f",(int)(slider.value) / 60,slider.maximumValue - (int)(slider.value) / 60 * 60.0];
//    NSLog(@"%@",self.currentLabel.text);
    if (!self.AllTimeLabel.text) {
        NSLog(@"jasdfs==========");
        self.AllTimeLabel.text = [NSString stringWithFormat:@"%0d:%.2f",(int)(slider.maximumValue) / 60, slider.maximumValue - (int)(slider.value) / 60 * 60.0];
    }
//    NSLog(@"%@",self.AllTimeLabel.text);
    
}
- (void)timerAction {
    
    self.TImerSlider.value = self.audioPlayer.progress;
    if (self.audioPlayer.state == STKAudioPlayerStateStopped && self.audioPlayer.stopReason == STKAudioPlayerStopReasonEof) {
        [self.PlayOrPauseBtn setImage:[UIImage imageNamed:@"Unknown-6"] forState:UIControlStateNormal];
//        [self lrc:[[STKAudioPlayerHandle shareSTKAudioPlayerHandle] currentOfMusic]];
//        [self.tableView reloadData];
    }
    
    if (self.audioPlayer.state == STKAudioPlayerStatePaused) {
        self.isRotation = NO;
        [self rotationOrStop];
    }
    self.TImerSlider.maximumValue = self.audioPlayer.duration;
//    NSLog(@"%f",self.TImerSlider.maximumValue);
    if (self.currentOfMusic != [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] currentOfMusic]) {
        self.currentOfMusic = [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] currentOfMusic];
    }
    self.currentLabel.text = [NSString stringWithFormat:@"%0d:%.2f",((int)(self.TImerSlider.value)) / 60,  self.TImerSlider.value -(((int)(self.TImerSlider.value) / 60) * 60.0)];
//    NSLog(@"%@",self.currentLabel.text);
//    if ([self.AllTimeLabel.text isEqualToString:@"Label"]) {
        self.AllTimeLabel.text = [NSString stringWithFormat:@"%0d:%.2f",(int)(self.TImerSlider.maximumValue) / 60, self.TImerSlider.maximumValue - ((int)(self.TImerSlider.maximumValue) / 60) * 60.0];
//    }
    
}
- (IBAction)storeAction:(UIButton *)sender {
    //收藏与取消收藏
    if (!self.storeBtn.selected) {
        PosterDetailSongsModel *model = self.array[self.currentOfMusic];
        [[DataHandle shareDataBaseHandle] insertPosterSongsModel:model initoTable:@"store"];
        [self.storeBtn setImage:[UIImage imageNamed:@"439"] forState:UIControlStateNormal];
    } else if (self.storeBtn.selected) {
        PosterDetailSongsModel *model = self.array[self.currentOfMusic];
        [[DataHandle shareDataBaseHandle] deletePosterSongsModel:model intoTable:@"store"];
        [self.storeBtn setImage:[UIImage imageNamed:@"438"] forState:UIControlStateNormal];
    }
    self.storeBtn.selected = !self.storeBtn.selected;
}


//- (IBAction)loginBtn:(id)sender {
//    [UIView animateWithDuration:0.2 animations:^{
//        self.shareView.frame = CGRectMake(0, HEIGHT, WIDTH, HEIGHT);
//        
//    }];
//    self.isShare = YES;
//    //登录第二步
//    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToTencent];
//    
//    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
//        
//        //          获取微博用户名、uid、token等
//        
//        if (response.responseCode == UMSResponseCodeSuccess) {//登录成功
//            
//            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToTencent];
//            
//            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
//            
//            
//            //登录第三步 ：在登录成功后 获取用户信息
//            //获取accestoken以及新浪用户信息，得到的数据在回调Block对象形参respone的data属性
//            [[UMSocialDataService defaultDataService] requestSnsInformation:UMShareToTencent  completion:^(UMSocialResponseEntity *response){
//                NSLog(@"SnsInformation is %@",response.data);
//                self.isShare = NO;
//                [self.tableView reloadData];
//            }];
//            
//            
//            
//        }});
//
//}
//
//
//
//- (IBAction)shareBtn:(UIButton *)sender {
//    
//    /**
//     根据平台名，返回平台对象
//     
//     @param platformName sns平台名
//     
//     @return UMSocialSnsPlatform 平台对象
//     */
//    
////    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
//    [UIView animateWithDuration:0.2 animations:^{
//        self.shareView.frame = CGRectMake(0, HEIGHT, WIDTH, HEIGHT);
//        
//    }];
//    self.isShare = YES;
//    /**
//     Sns平台类，用`platformName`作为标识，指定显示名称、显示的图片，点击之后的响应。
//     */
////    snsPlatform.displayName = @"新浪";
////    snsPlatform.loginName = @"网易";
//    
//    UMSocialSnsPlatform *snsPlatform2 = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToTencent];
//    snsPlatform2.displayName = @"腾讯微博";
//    UMSocialSnsPlatform *snsPlayform3 = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToQzone];
//    snsPlayform3.displayName = @"微信朋友圈";
//    
//    
//    //分享第二步
//    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"558936d367e58eb81b001298"
//                                      shareText:@"你要分享的文字"
//                                     shareImage:[UIImage imageNamed:@"Icon-29.png"]
//                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToTencent,UMShareToRenren,nil]
//                                       delegate:self];
//
//}
//
////- (void)didFinishGetUMSocialDataResponse:(UMSocialResponseEntity *)response {
////    NSLog(@"===========dhsfd");
////    self.isShare = NO;
////    [self createAnimation];
////    [self rotation];
////    [self.tableView reloadData];
////}
//
////-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response {
////    NSLog(@"===========dhsfd");
////    NSLog(@"%@",response);
////    self.isShare = NO;
////    [self createAnimation];
////    [self rotation];
////    [self.tableView reloadData];
////}

@end
